package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, header, err := r.FormFile("file")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	f, err := os.OpenFile("upload/" + filepath.Base(header.Filename), os.O_WRONLY | os.O_CREATE, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	io.Copy(f, file)
}

func downloadHandler(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	filename := filepath.Base(q.Get("filename"))
	if filename == "" {
		http.Error(w, "File name is required", http.StatusBadRequest)
		return
	}

	// 构建文件路径
	filePath := filepath.Join("download/", filename)

	// 打开文件
	file, err := os.Open(filePath)
	if err != nil {
		http.Error(w, "File not found", http.StatusNotFound)
		return
	}
	defer file.Close()

	// 获取文件信息
	fileInfo, err := file.Stat()
	if err != nil {
		http.Error(w, "Error accessing file", http.StatusInternalServerError)
		return
	}

	// 设置响应头
	w.Header().Set("Content-Disposition", "attachment; filename=" + filename)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))

	// 将文件内容写入到响应体
	_, err = io.Copy(w, file)
	if err != nil {
		http.Error(w, "Error reading file", http.StatusInternalServerError)
	}
}

func main() {
	http.HandleFunc("/upload", uploadHandler)
	http.HandleFunc("/download", downloadHandler)

	err := http.ListenAndServe(":9000", nil) // 设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe err: ", err)
	}
}
